package com.example.cardemo

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.cardemo.bean.TitleBean
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class NewActivity : AppCompatActivity() {
    private val titles: MutableList<TitleBean> = ArrayList()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_new)

        // 初始化数据
        titles.add(TitleBean("推荐", "top"))
        titles.add(TitleBean("国内", "guonei"))
        titles.add(TitleBean("国际", "guoji"))
        titles.add(TitleBean("娱乐", "yule"))
        titles.add(TitleBean("体育", "tiyu"))
        titles.add(TitleBean("军事", "junshi"))
        titles.add(TitleBean("科技", "keji"))
        titles.add(TitleBean("财经", "caijing"))
        titles.add(TitleBean("游戏", "youxi"))
        titles.add(TitleBean("汽车", "qiche"))
        titles.add(TitleBean("健康", "jiankang"))

        val tabLayout: TabLayout = findViewById(R.id.tab_layout)
        val modellistViewPager: ViewPager2 = findViewById(R.id.modellist_viewpager)

        modellistViewPager.adapter = object : FragmentStateAdapter(this) {
            override fun createFragment(position: Int): Fragment {
                val title = titles[position].py_title
                return TabNewsFragment.newInstance(title.toString())
            }

            override fun getItemCount(): Int {
                return titles.size
            }
        }

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                modellistViewPager.setCurrentItem(tab?.position ?: 0, false)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

        //tabLayout和viewPager2关联
        val tabLayoutMediator = TabLayoutMediator(tabLayout, modellistViewPager, true) { tab, position ->
            tab.text = titles[position].title
        }

        tabLayoutMediator.attach()
    }
}